package cn.acewill.yxd.yunxundian.adapter;

import android.annotation.SuppressLint;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;

import org.xutils.DbManager;
import org.xutils.ex.DbException;
import org.xutils.x;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Locale;

import cn.acewill.yxd.yunxundian.BaseActivity;
import cn.acewill.yxd.yunxundian.R;
import cn.acewill.yxd.yunxundian.YXDAPP;
import cn.acewill.yxd.yunxundian.model.Employee;
import cn.acewill.yxd.yunxundian.model.Schedule;
import cn.acewill.yxd.yunxundian.model.Shop;
import cn.acewill.yxd.yunxundian.pubClass.pubClass;

/**
 * Created by XXX on 2017/9/11.
 */

public class TodayTaskrecycleAdapter extends RecyclerView.Adapter<TodayTaskrecycleAdapter.MyViewHolder> {
    private Context context;
    private List<Schedule> taskList;
    private int currentitem=-1;
    private moreTaskCallBack moreTaskCallBack;
    protected YXDAPP yxdapp=new YXDAPP();
    protected DbManager db = x.getDb(yxdapp.getDaoConfig());
    private Employee employee;
    private Date  today;
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",Locale.getDefault());

    public  TodayTaskrecycleAdapter(Context context, List<Schedule> taskList,moreTaskCallBack moreTaskCallBack, Employee emp){
        this.context =context;
        this.taskList=taskList;
        this.moreTaskCallBack=moreTaskCallBack;
        this.employee=emp;
        //只需查询一次
        try {
            if (taskList==null||taskList.size()==0){
                employee=null;
            }else{
                employee=db.selector(Employee.class).where("ID","=",taskList.get(0).getToUserId()).findFirst();
            }

       } catch (DbException e) {
           e.printStackTrace();
       }
    }

    public interface moreTaskCallBack{
        void Click(Schedule bean) throws DbException;
        void submitClick(Schedule bean);
        void shopSignClick(Schedule bean);
        void onScorller(int position);
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.today_task,parent,false);
        MyViewHolder holder = new MyViewHolder(view);
        try {
            today =sdf.parse(BaseActivity.getNowDate());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return holder;
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        Schedule schedule = taskList.get(position);
        holder.binTag(schedule);

        //头像修复
//        if (employee.getEmpImage()!=null){
//            String path= pubClass.pictureSavePath +employee.getEmpImage();
//            Glide.with(context).load(path).error(R.mipmap.icon_error)
//                    .into(holder.myPhoto);
//        }else{
//            holder.myPhoto.setImageResource(R.mipmap.icon_logo);
//        }
        holder.userName.setText(String.valueOf(getShopName(schedule.getShopID())));
        String text=schedule.getSchStartTime().replace('T',' ');
        if (text.length()>19)
            holder.taskDate.setText(text.substring(0,text.length()-4));
        else
            holder.taskDate.setText(text);
        //holder.taskHours.setText(bean.getSchStartTime());
        holder.taskDesc.setText(schedule.getTitle());
        if (currentitem==position){
            holder.hideArea.setVisibility(View.VISIBLE);
            moreTaskCallBack.onScorller(position);
        }else{
            holder.hideArea.setVisibility(View.GONE);
        }
        //用view充当，去掉最后一个分割线
        if (taskList!=null && taskList.size()>0){
            if (position==taskList.size()-1){
                holder.lineView.setVisibility(View.GONE);
            }
        }
        //计算距时间
        String startTime  = schedule.getSchStartTime();
        if (startTime!=null){
            String array = startTime.replace("T"," ");
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
            try {
                Date date1=sdf.parse(array);
                GregorianCalendar cal1 = new GregorianCalendar();
                GregorianCalendar cal2 = new GregorianCalendar();
                cal1.setTime(date1);
                cal2.setTime(today);
                Long time = (cal1.getTime().getTime()-cal2.getTime().getTime())/(1000*60*60*24);
                if (time>0) holder.distanceTaskData.setText(context.getResources().getString(R.string.task_status_distance_start)+String.valueOf(Math.abs(time))+context.getResources().getString(R.string.task_day));
                if (time<0)holder.distanceTaskData.setText(context.getResources().getString(R.string.task_status_distance_start)+String.valueOf(Math.abs(time))+context.getResources().getString(R.string.task_day));
                else holder.distanceTaskData.setText(R.string.task_status_today);

            } catch (ParseException e) {
                e.printStackTrace();
            }

        }

    }

    @Override
    public int getItemCount() {
        return taskList==null?0:taskList.size();
    }

    class MyViewHolder extends RecyclerView.ViewHolder{

    //    ImageView myPhoto;
        TextView userName;
        TextView taskDate;
        TextView taskHours;
        TextView taskDesc;
        TextView submitData;
        Button moreTask;
        Button shopSign;
        RelativeLayout showArea;
        LinearLayout hideArea;
        View lineView;
        TextView distanceTaskData;

        private MyViewHolder(View itemView) {
            super(itemView);
       //     myPhoto= (ImageView) itemView.findViewById(R.id.myPhoto);
            userName=  itemView.findViewById(R.id.userName);
            taskDate=  itemView.findViewById(R.id.taskDate);
            taskHours=  itemView.findViewById(R.id.taskHours);
            taskDesc=  itemView.findViewById(R.id.taskDesc);
            moreTask=  itemView.findViewById(R.id.moreTask);
            shopSign=itemView.findViewById(R.id.shopSign);
            hideArea=  itemView.findViewById(R.id.hideArea);
            showArea=  itemView.findViewById(R.id.showArea);
            submitData=  itemView.findViewById(R.id.submitData);
            lineView=itemView.findViewById(R.id.lineView);
            distanceTaskData =  itemView.findViewById(R.id.distanceTaskData);

            showArea.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(getLayoutPosition()==currentitem){
                        currentitem=-1;
                    }else{
                        //记录上一次点击的position
                        int olderItem = currentitem;
                        if (olderItem!=-1){
                            notifyItemChanged(olderItem);
                        }
                        currentitem=getLayoutPosition();
                    }
                   notifyItemChanged(getLayoutPosition());
                }
            });
            shopSign.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    moreTaskCallBack.shopSignClick((Schedule) shopSign.getTag());
                }
            });

            //执行任务
            moreTask.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    try {
                        moreTaskCallBack.Click((Schedule)moreTask.getTag());
                    } catch (DbException e) {
                        e.printStackTrace();
                    }
                }
            });
            submitData.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    moreTaskCallBack.submitClick((Schedule)submitData.getTag());
                }
            });
        }
        private void binTag(Schedule schedule){
            moreTask.setTag(schedule);
            shopSign.setTag(schedule);
            submitData.setTag(schedule);
        }

    }

    private String getShopName(int shopid){
        try {
            Shop shop = db.selector(Shop.class).where("ID", "=", String.valueOf(shopid)).findFirst();
            if (shop != null)
                return shop.getShopName();
            else
                return "";
        }
        catch (DbException e) {
            e.printStackTrace();
        }
        return "";
    }

}
